package school.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import school.domain.Info;
import school.domain.Personal;
import school.mapper.PersonalMapper;
import school.support.BaseController;
import school.support.pojo.PersonalPo;
import school.support.util.ParamUtils;
import tk.mybatis.mapper.entity.Example;

@RequestMapping("personal")
@Controller
public class PersonalController extends BaseController {

    @Autowired
    private PersonalMapper personalMapper;

    /**
     * 档案列表
     *
     * @param personalPo
     * @param pageNum
     * @param model
     * @return
     */
    @RequestMapping("list")
    private String list(PersonalPo personalPo, @RequestParam(defaultValue = "1") Integer pageNum, Model model) {
        Example example = new Example(Info.class);
        Example.Criteria criteria = example.createCriteria();
        if (personalPo.getUsername() != null) {
            criteria.andCondition("u.name like '%" + personalPo.getUsername() + "%'");
        }
        /**
         * 如果是医生     只能看到自己负责的用户
         */
        if (sessionUser().getType().equalsIgnoreCase("doctor")) {
            criteria.andCondition("u.doctor = '" + sessionUser().getId() + "'");
        }

        PageHelper.startPage(pageNum, pageSize);
        PageInfo<PersonalPo> pageInfo = new PageInfo<>(personalMapper.selectPoByExample(example), 5);
        model.addAttribute(pageInfo);
        model.addAttribute("url", request.getRequestURI() + "?" + ParamUtils.params2String(request));
        return "personal/list";
    }

    /**
     * 档案详情
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("detail/{id}")
    public String detail(@PathVariable Integer id, Model model) {
        Personal personal = null;
        if (id == 0) {
            Integer userid = sessionUser().getId();
            personal = personalMapper.selectByUser(userid);
        } else {
            personal = personalMapper.selectByPrimaryKey(id);
        }
        if(personal == null) personal = new Personal();
        model.addAttribute("personal", personal);
        return "personal/detail";
    }

    /**
     * 修改信息
     *
     * @param personal
     * @return
     */
    @RequestMapping("update")
    public String update(Personal personal) {
        if (personal.getId() == null || personal.getId() == 0) {
            personal.setUserid(sessionUser().getId());
            personalMapper.insertSelective(personal);
        } else {
            personalMapper.updateByPrimaryKeySelective(personal);
        }

        return refresh();
    }


}
